﻿using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace DoNet.Utils
{
    public class SignHelper
    {
        /// <summary>
        /// Md5签名算法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string CalMd5(string str)
        {
            var md5 = MD5.Create();
            var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
            var sb = new StringBuilder();
            foreach (byte b in bs)
            {
                sb.Append(b.ToString("x2"));
            }
            //所有字符转为大写
            return sb.ToString().ToUpper();
        }

        /// <summary>
        /// SHA签名算法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string CalSHA1(string str)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] bytesIn = Encoding.UTF8.GetBytes(str);
            byte[] bytesOut = sha1.ComputeHash(bytesIn);
            sha1.Dispose();
            string result = BitConverter.ToString(bytesOut);
            result = result.Replace("-", "");
            return result;
        }

        /// <summary>
        /// HMAC-SHA256签名算法
        /// </summary>
        /// <param name="plaintext"></param>
        /// <param name="salt"></param>
        /// <returns></returns>
        public static string CalcHMACSHA256Hash(string plaintext, string salt)
        {
            string result = "";
            var enc = Encoding.UTF8;
            byte[]
            baText2BeHashed = enc.GetBytes(plaintext),
            baSalt = enc.GetBytes(salt);
            HMACSHA256 hasher = new HMACSHA256(baSalt);
            byte[] baHashedText = hasher.ComputeHash(baText2BeHashed);
            result = string.Join("", baHashedText.ToList().Select(b => b.ToString("x2")).ToArray());
            return result.ToUpper();
        }
    }
}
